<template>
  <div class="course-wrap">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-fa fa-book"></i> 课程管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="container">
      <div class="query-form">
        <el-row :gutter="20">
          <el-col :span="2">
            <el-button @click="create" icon="el-icon-plus">创建</el-button>
          </el-col>
          <el-col :offset="10" :span="3">
            <el-select v-model="entityForm.term" placeholder="学期">
              <el-option
                v-for="item in courseTerm"
                :key="item.term"
                :label="item.term"
                :value="item.term"
              />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-date-picker
              v-model="classDates"
              type="date"
              placeholder="选择日期"
            />
          </el-col>
          <el-col :offset="2" :span="3">
            <el-button
              @click="startScheduling"
              icon="el-icon-search"
              type="primary"
              >开始排课</el-button
            >
          </el-col>
        </el-row>
      </div>

      <el-row justify="center" type="flex">
        <el-pagination
          :current-page.sync="pageIndex"
          :page-size="pageSize"
          :total="pageSize * pageCount"
          @current-change="getPage"
          background
          layout="prev, pager, next"
        >
        </el-pagination>
      </el-row>

      <div class="table">
        <el-table :data="tableData" stripe>
          <el-table-column label="学期" prop="term" />
          <el-table-column label="课程号" prop="courseId" />
          <el-table-column label="课程名" prop="courseName" width="200px" />
          <el-table-column label="课程状态" prop="courseStatus" />
          <el-table-column label="课时" prop="hours" />
          <el-table-column label="课程等级" prop="courseLevel" />
          <el-table-column align="center" label="操作" width="200px">
            <template slot-scope="scope">
              <el-button
                @click="edit(scope.row.courseId)"
                size="mini"
                type="success"
                >编辑
              </el-button>
              <el-button
                @click="deleteItem(scope.row.courseId)"
                size="mini"
                type="danger"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="custom-progress">
          <el-progress v-if="showProgress" :percentage="progressPercentage" />
        </div>
      </div>

      <el-dialog :visible.sync="editing" title="编辑" width="30%">
        <el-form :model="entityForm" label-width="70px" ref="form">
          <el-form-item label="课程学期">
            <el-select v-model="entityForm.term" placeholder="学期">
              <el-option
                v-for="term in days"
                :key="term"
                :label="term"
                :value="term"
              />
            </el-select>
            <!-- <el-select v-model="courseTime">
              <el-option
                :key="index"
                :label="item"
                :value="index"
                v-for="(item, index) in times"
              >
              </el-option>
            </el-select> -->
          </el-form-item>
          <el-form-item label="课程名">
            <el-input v-model="entityForm.courseName"></el-input>
          </el-form-item>
          <!-- <el-form-item label="授课教师">
            <el-select placeholder="请选择教师" v-model="entityForm.teacherId">
              <el-option
                :key="index"
                :label="item.name"
                :value="item.id"
                v-for="(item, index) in teachers"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="课时">
            <el-input type="number" v-model="entityForm.hours"></el-input>
          </el-form-item>
          <el-form-item label="课程等级">
            <el-input v-model="entityForm.courseLevel"></el-input>
          </el-form-item>
          <el-form-item label="假日状态">
            <el-select
              placeholder="0代表未排课,1已排课,2已结课"
              v-model="entityForm.status"
              :value="0"
            >
              <el-option
                :key="index"
                :label="item.label"
                :value="item.value"
                v-for="(item, index) in statusList"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="排课顺序">
            <el-input v-model="entityForm.courseOrder"></el-input>
          </el-form-item>
          <!-- <el-form-item label="时长(节)">
            <el-input type="number" v-model="courseLength"></el-input>
          </el-form-item>
          <el-form-item label="上课地点">
            <el-input v-model="entityForm.location"></el-input>
          </el-form-item> -->
          <!-- <el-form-item label="学分">
            <el-input type="number" v-model="entityForm.credit"></el-input>
          </el-form-item>
          <el-form-item label="最大容量">
            <el-input type="number" v-model="entityForm.maxSize"></el-input>
          </el-form-item> -->
          <!--<el-form-item label="考试时间">-->
          <!--<el-date-picker-->
          <!--format="yyyy-MM-dd HH:mm"-->
          <!--type="datetime"-->
          <!--v-model="entityForm.examDate"-->
          <!--value-format="yyyy-MM-dd HH:mm"-->
          <!--&gt;-->
          <!--</el-date-picker>-->
          <!--</el-form-item>-->
          <!-- <el-form-item label="考试地点">
            <el-input v-model="entityForm.examLocation"></el-input>
          </el-form-item> -->
        </el-form>
        <span class="dialog-footer" slot="footer">
          <el-button @click="save" type="primary">确 定</el-button>
          <el-button @click="editing = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import * as api from "../../api/admin/course";

export default {
  name: "AdminCourse",
  data() {
    return {
      queryForm: {},
      entityForm: {
        term: ""
      },
      showProgress: false, // 是否显示进度条
      progressPercentage: 0, // 进度条百分比
      tableData: [],
      pageSize: api.pageSize,
      pageCount: 1,
      pageIndex: 1,
      editing: false,
      teachers: [],
      classDates: null,
      courseTerm: [],
      statusList: [
        { label: "未排课", value: 0 }, //0代表未排课，1已排课，2已结课
        { label: "已排课", value: 1 },
        { label: "已结课", value: 2 }
      ],
      // courseTime: "",
      courseLength: 0,
      days: ["2023-1", "2023-2", "2024-1", "2024-2", "2025-1", "2025-2"]
      // times: [
      //   "第一节",
      //   "第二节",
      //   "第三节",
      //   "第四节",
      //   "第五节",
      //   "第六节",
      //   "第七节",
      //   "第八节",
      //   "第九节"
      // ]
    };
  },
  methods: {
    async loadData() {
      try {
        const res = await api.queryAllSemester();
        console.log("API Response:", res.data);
        this.courseTerm = [res.data.term]; // Assuming res.data is the array ["2023-1"]
        // 这里可以放置其他与数据处理有关的代码
      } catch (error) {
        console.error("API Error:", error);
      }
    },

    query() {
      api.getPageCount().then(res => {
        this.pageCount = res;
        this.pageIndex = 1;
        this.getPage(1);
      });
    },
    getPage(pageIndex) {
      api.getPage(pageIndex).then(res => {
        this.tableData = res;
      });
    },
    create() {
      this.entityForm = {
        term: "",
        courseId: -1,
        courseName: "",
        courseStatus: "",
        hours: "",
        courseLevel: ""
      };
      this.editing = true;
    },
    selectedDepartment() {
      api.queryAllSemester().then(res => {
        console.log("1111" + res);
        this.courseTerm = res;
      });
    },
    startScheduling() {
      if (this.entityForm.term && this.classDates) {
        const formattedDate = this.classDates.toISOString().split("T")[0];
        console.log("formattedDate:" + formattedDate);
        const requestData = {
          term: this.entityForm.term,
          classDates: formattedDate
        };

        // 显示进度条
        this.showProgress = true;
        this.progressPercentage = 0;

        // 模拟进度增加至100%
        const interval = setInterval(() => {
          this.progressPercentage += 20;
          if (this.progressPercentage >= 100) {
            clearInterval(interval);
            // 5秒后显示排课成功消息
            setTimeout(() => {
              this.$message.success("排课成功！");
              this.showProgress = false; // 隐藏进度条
            }, 1000); // 等待5秒后隐藏进度条
          }
        }, 500);

        // 调用排课API
        api.arrange(requestData).catch(error => {
          clearInterval(interval); // 清除定时器
          this.showProgress = false; // 隐藏进度条
          console.error("API Error:", error);
          this.$message.error("排课失败！");
        });
      } else {
        this.$message.warning("请选择学期和日期");
      }
    },

    edit(courseId) {
      api.get(courseId).then(res => {
        this.entityForm = res;
        this.editing = true;
      });
    },
    save() {
      let day = this.courseDay + 1;
      let time = this.courseTime + 1;
      this.entityForm.time = day + "-" + time + "-" + this.courseLength;

      if (this.entityForm.courseId === -1) {
        api.create(this.entityForm).then(() => {
          this.finishSave();
        });
      } else {
        api.update(this.entityForm).then(() => {
          this.finishSave();
        });
      }
    },
    finishSave() {
      this.$message.success("成功");
      this.getPage(this.pageIndex);
      this.editing = false;
    },
    deleteItem(courseId) {
      api.deleteItem(courseId).then(() => {
        this.$message.success("删除成功");
        this.getPage(this.pageIndex);
      });
    }
  },
  created() {
    this.selectedDepartment();
    this.query();
  }
};
</script>

<style scoped>
.custom-progress {
  width: 100%;
  height: 20px;
  background-color: #f0f0f0; /* 进度条背景颜色 */
  border-radius: 10px; /* 圆角 */
  position: relative;
}

.el-progress {
  border-radius: 10px; /* 圆角 */
  height: 100%;
}

.el-progress__text {
  line-height: 20px; /* 文字垂直居中 */
  color: #fff; /* 文字颜色 */
  font-weight: bold;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}
</style>
